from django.shortcuts import render
import datetime
from django.contrib import messages
from django.db.models import Q

# Create your views here.
from .models import *
from django.http import HttpResponse


def proc_order(request):
    return render(request, '../templates/Procurement/order-page.html')


def proc_check(request):
    return render(request, '../templates/Procurement/proc-check.html')


def proc_plan(request):
    return render(request, '../templates/Procurement/proc-plan.html')


def index_views(request):
    replenish = ShowReplenishRequest()
    plan = ShowProcurePlan()
    order = ShowOrder()
    quality = ShowQuality()
    return render(request, '../templates/Procurement/index.html',
                  {"replenish": replenish, "plan": plan, "order": order, "quality": quality})


def ShowReplenishRequest():
    replenish = ReplenishRequest.objects.filter().exclude(over=1).all()
    return replenish


def ShowProcurePlan():
    plan = ProcurePlan.objects.filter(~Q(over=1))
    print(plan)
    for item in plan:
        # goods_id = ReplenishRequest.objects.filter(procure_id=item.procure.procure_id).first().goods.goods_id
        goods_id = item.procure.goods.goods_id
        good = GoodsInfo.objects.filter(goods_id=goods_id).first()
        item.procure_content = good.goods_name
        item.money = good.gprice * item.procure.request_num / 2
    return plan


def ShowOrder():
    order = ProcureOrder.objects.filter().exclude(over=1).all()
    for item in order:
        logi = item.order_logi_procure.all().first()
        if logi.arrival_time.replace(tzinfo=None) > datetime.datetime.now():
            logi.logi_status = '未送达'
        else:
            logi.logi_status = '已送达'
        logi.save()
    return order


def ShowQuality():
    quality = QualityInfo.objects.filter().exclude(over=1).all()
    for item in quality:
        logi = item.logi
        if item.quality_status == '核验完成':
            item.pro = str(100)
            continue
        else:
            if logi.logi_status == '未送达':
                item.quality_status = '未送达'
            else:
                item.quality_status = '已送达，未核验'
            item.save()
            status = item.quality_status
            pro = 0
            if status == '未送达':
                pro = 25
            elif status == '已送达，未核验':
                pro = 75
            item.pro = str(pro)
    return quality


def create_plan(request):  # 进入创建采购计划页面
    if request.method == 'POST':
        res = {}
        procure_id = request.POST['采购需求']
        # print(procure_id)
        # print(1)
        replenish = ReplenishRequest.objects.filter(procure_id=procure_id).first()
        content = replenish.goods.goods.goods_name
        return render(request, '../templates/Procurement/proc-plan.html',
                      {"procure_id": procure_id, "content": content})
    else:
        return render(request, '../templates/Procurement/index.html')


def insert_plan(request):  # 生成采购计划，并插入数据库
    if request.method == "POST":
        id = request.POST['id']
        principle = request.POST['principle']
        replenish = ReplenishRequest.objects.filter(procure_id=id).first()
        content = replenish.goods.goods.goods_name
        project_intro = "采购" + content
        ProcurePlan.objects.create(procure=replenish, check_status='未审批', project_intro=project_intro,
                                   procure_rule=principle, procure_content=content, over=0)
        return render(request, '../templates/Procurement/proc-plan.html')


def insert_order(request):  # 生成采购计划，并插入数据库
    if request.method == 'POST':
        replenish1 = request.POST['采购计划']
        # print(1)
        # print(request)
        plan = ProcurePlan.objects.filter(procure=replenish1).first()
        if plan.check_status != '审批通过':
            messages.error(request, '审批未通过或未审批！请在审批后进行匹配操作。')
            replenish = ShowReplenishRequest()
            plan = ShowProcurePlan()
            order = ShowOrder()
            quality = ShowQuality()
            return render(request, '../templates/Procurement/index.html',
                          {"replenish": replenish, "plan": plan, "order": order, "quality": quality})
        replenish1 = plan.procure
        # print(plan)
        sup = SupplyInfo.objects.filter(sup_serve__icontains=plan.procure_content).order_by('sup_level').first()
        num = replenish1.request_num
        price = replenish1.goods.goods.gprice / 2.5
        ProcureOrder.objects.create(procure=plan, sup=sup, procure_price=price, procure_num=num, over=0)
        order1 = ProcureOrder.objects.filter(procure=plan).first()
        insert_logi(order1, replenish1)
        insert_quality(order1)

        replenish = ShowReplenishRequest()
        plan = ShowProcurePlan()
        order = ShowOrder()
        quality = ShowQuality()
        return render(request, '../templates/Procurement/index.html',
                      {"replenish": replenish, "plan": plan, "order": order, "quality": quality})
    else:
        return render(request, '../templates/Procurement/index.html')


def insert_quality(order):
    logi = order.order_logi_procure.all().first()
    sup = logi.sup
    procure = order.procure.procure
    quality_result = '未核验'
    if logi.logi_status == '未送达':
        quality_status = '未送达'
    else:
        quality_status = '已送达，未核验'
        quality_result = '未核验'
    QualityInfo.objects.create(procure=procure, logi=logi, sup=sup, quality_status=quality_status,
                               quality_result=quality_result, over=0)


def insert_logi(order1, replenish1):
    start_time = replenish1.request_time + datetime.timedelta(days=1)
    arrival_time = start_time + datetime.timedelta(days=3)
    if arrival_time.replace(tzinfo=None) > datetime.datetime.now():
        logi_status = '未送达'
    else:
        logi_status = '已送达'
    LogisticsInfo.objects.create(logi_id='logi_' + replenish1.procure_id, sup=order1.sup, procure=order1,
                                 start_time=start_time, logi_status=logi_status, arrival_time=arrival_time, over=0)


def ShowLogi(request):
    if request.method == 'POST':
        logi_id = request.POST['物流单']
        # print(logi_id)
        logi = LogisticsInfo.objects.filter(logi_id=logi_id).first()
        # print(logi)
        return render(request, '../templates/Procurement/logi.html', {'logi': logi})


def check(request):
    if request.method == 'POST':
        proc_id = request.POST['订单号']
        e_id = request.POST['工号']
        result = request.POST['结果']
        procure = ReplenishRequest.objects.get(procure_id=proc_id)
        quality1 = QualityInfo.objects.get(procure=procure)
        logi = quality1.logi
        if logi.logi_status == '未送达':
            messages.error(request, "商品暂未送达，请在送达后核验。")
            return render(request, '../templates/Procurement/proc-check.html', )
        quality1.quality_status = '核验完成'
        quality1.quality_result = result
        quality1.save()

        replenish = ShowReplenishRequest()
        plan = ShowProcurePlan()
        order = ShowOrder()
        quality = ShowQuality()
        return render(request, '../templates/Procurement/index.html',
                      {"replenish": replenish, "plan": plan, "order": order, "quality": quality})


def get_plan(request):
    if request.method == 'POST':
        proc_id = request.POST['p_id']
        replenish1 = ReplenishRequest.objects.filter(procure_id=proc_id).first()
        plan = ProcurePlan.objects.filter(procure=replenish1).first()
        return render(request, '../templates/Procurement/order-page.html', {'plan': plan})


def check_plan(request):
    if request.method == 'POST':
        permission = request.POST['permit']
        # print(permission)
        proc_id = request.POST['p_id']
        replenish1 = ReplenishRequest.objects.filter(procure_id=proc_id).first()
        plan = ProcurePlan.objects.filter(procure=replenish1).first()
        if permission == '是':
            plan.check_status = '审批通过'
        elif permission == '否':
            plan.check_status = '审批未通过'
        plan.save()
        messages.success(request, "审批完成")

        replenish = ShowReplenishRequest()
        plan = ShowProcurePlan()
        order = ShowOrder()
        quality = ShowQuality()
        return render(request, '../templates/Procurement/index.html',
                      {"replenish": replenish, "plan": plan, "order": order, "quality": quality})


def good_sub(request):
    if request.method == 'POST':
        id = request.POST['交付单']
        replenish1 = ReplenishRequest.objects.filter(procure_id=id).first()
        plan = ProcurePlan.objects.filter(procure=replenish1).first()
        order = ProcureOrder.objects.filter(procure=plan).first()
        logi = LogisticsInfo.objects.filter(procure=order).first()
        quality = QualityInfo.objects.filter(procure=replenish1).first()
        good_id = replenish1.goods.goods.goods_id
        # print(good_id)
        good_name = replenish1.goods.goods.goods_name
        in_num = replenish1.request_num
        in_time = datetime.datetime.now()

        if quality.quality_result == "合格":
            StockIn.objects.create(procure=id, goods_id=good_id, goods_name=good_name,
                                   in_num=in_num, in_time=in_time, in_status=0)
            replenish1.over = 1
            replenish1.save()
            plan.over = 1
            plan.save()
            order.over = 1
            order.save()
            logi.over = 1
            logi.save()
            quality.over = 1
            quality.save()

        else:
            messages.error(request, '质检未通过，无法交付！')

        replenish = ShowReplenishRequest()
        plan = ShowProcurePlan()
        order = ShowOrder()
        quality = ShowQuality()
        return render(request, '../templates/Procurement/index.html',
                      {"replenish": replenish, "plan": plan, "order": order, "quality": quality})


def history_page(request):
    replenish = ShowReplenishRequest_history()
    plan = ShowProcurePlan_history()
    order = ShowOrder_history()
    quality = ShowQuality_history()
    return render(request, '../templates/Procurement/history.html',
                  {"replenish": replenish, "plan": plan, "order": order, "quality": quality})


def ShowReplenishRequest_history():
    replenish = ReplenishRequest.objects.filter(over=1)
    return replenish


def ShowProcurePlan_history():
    plan = ProcurePlan.objects.filter(over=1)
    print(plan)
    for item in plan:
        # goods_id = ReplenishRequest.objects.filter(procure_id=item.procure.procure_id).first().goods.goods_id
        goods_id = item.procure.goods.goods_id
        good = GoodsInfo.objects.filter(goods_id=goods_id).first()
        item.procure_content = good.goods_name
        item.money = good.gprice * item.procure.request_num / 2
    return plan


def ShowOrder_history():
    order = ProcureOrder.objects.filter(over=1)
    return order


def ShowQuality_history():
    quality = QualityInfo.objects.filter(over=1)
    for item in quality:
        item.pro = str(100)
    return quality


'''
def ShowReplenishRequest(request):
    replenish = ReplenishRequest.objects.all()
    plan = ProcurePlan.objects.all()
    order = ProcureOrder.objects.all()
    quality = QualityInfo.objects.all()
    # goods = GoodsInfo.objects.all()
    for item in plan:
        # goods_id = ReplenishRequest.objects.filter(procure_id=item.procure.procure_id).first().goods.goods_id
        goods_id = item.procure.goods.goods_id
        item.procure_content = GoodsInfo.objects.filter(goods_id=goods_id).first().goods_name
    # order = ProcureOrder.objects.select_related("procure")
    for item in quality:
        status = item.quality_status
        pro = 0
        if status == '未送达':
            pro = 0
        elif status == '已送达，未核验':
            pro = 50
        elif status == '核验完成':
            pro = 100
        item.pro = str(pro)
    return render(request, '../templates/Procurement/index.html',
                  {"replenish": replenish, "plan": plan, "order": order, "quality": quality})
'''
